 package com.itic.market.mobile.login;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.sys.relation.persistence.model.UserRole;
import com.itic.appbase.applications.sys.user.persistence.model.SysUser;
import com.itic.appbase.applications.sys.user.service.SysUserService;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.MD5Helper;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.RandomStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.qcode.QcodeUtils;
import com.itic.market.mobile.base.BaseMobileInterface;
import com.itic.market.system.markettoken.persistence.model.MarketToken;
import com.itic.market.system.user.persistence.model.MarketUser;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.Notification; 


/**
 * 用户登入接口类
 * @author 许小宝
 * 2017年07月25日  14时11分
 */
@Controller
@RequestMapping(value="/mobile/login")
public class MarketLoginInterface
     extends BaseMobileInterface {
    
	private static final String RESET_PWD = "123456";
	
	private static final String APP_KEY = "97b60aeccea9d113d6a1b164";
	
	private static final String SECREAT = "fc9a01780fdeb90b43e736f3";
	@Autowired
	private SysUserService sysUserService;
	  
	public String getRandomInvitingCode(){
		 String code = RandomStringHelper.randomNumStr(6);
		 //查找下数据库中有没有人使用过
		 MarketUser user = marketUserService.getUserByInvitingCode(code);
		 if( null == user ){
			 return code;
		 }else{
			 return getRandomInvitingCode();
		 }
	}
	
    /**
     * APP用户注册成商家
     * @return
    
    @RequestMapping(value="/reg")
    @ResponseBody
    public Map<String,Object> reg(HttpServletRequest request,HttpServletResponse response,String openid,String unionId,String userNickName,String userHeadImg,String invitingCode){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( (StringHelper.isNotBlank(unionId) || StringHelper.isNotBlank(openid)) && StringHelper.isNotBlank(invitingCode) ){
    			//验证邀请码是否正确
    			MarketUser invitingUser = marketUserService.getUserByInvitingCode(invitingCode);
    			
    			if( null != invitingUser ){
    				//验证opendid 是否注册 
        			//MarketUser isExisted = marketUserService.getUserByOpenid(openid);
        			MarketUser unionExisted = marketUserService.getUserByUnionId(unionId);
        			if( null == unionExisted ){
        				MarketUser regUser = regUser(openid, unionId, userHeadImg, userNickName, invitingUser.getId());
            			//生成一个TOKEN 
        				MarketToken createToken = createToken(regUser);
            			//更新数据库
        				
        				String onePeople="0";
        				if( StringHelper.isNotBlank(invitingUser.getSuccessPeople()) ){
        					onePeople = invitingUser.getSuccessPeople();
        				}
        				onePeople = NumberStringHelper.addString(onePeople, "1");
        				invitingUser.setSuccessPeople(onePeople);
        				
        				//判断有没有上上级
        				MarketUser topInviting = marketUserService.get(invitingUser.getInvitingId());
        				if( null != topInviting ){
        					String topPeople="0";
        					if( StringHelper.isNotBlank(topInviting.getSuccessPeople()) ){
        						topPeople = topInviting.getSuccessPeople();
            				}
        					topPeople = NumberStringHelper.addString(topPeople, "1");
        					topInviting.setSuccessPeople(topPeople);
        				}
        				
        				 String roleIds = sysSettingService.getByKey("MARKET_ROLE_ID");
        				 String orgCode = sysSettingService.getByKey("MARKET_ORG_CODE");
        				//添加一个登入后台的用户
        				SysUser sysUser = new SysUser();
        				sysUser.setUsername(regUser.getInvitingCode());//邀请码作为用户的登入名称
        				String realName = "";
        				if( StringHelper.isNotBlank(regUser.getUserNickName()) ){
        					realName = regUser.getUserNickName();
        				}else{
        					realName = "匿名用户";
        					regUser.setUserNickName("匿名用户");
        				}
        				sysUser.setRealname(realName);
        				
        				sysUser.setOrg(orgCode);
        				sysUser.setType("1");
        				sysUser.setIsUsable("1");
        	            sysUser.setId(IdGen.uuid());
        	            sysUser.setPassword(MD5Helper.md5DoubleSalt(RESET_PWD, sysUser.getUsername()));

        	            List<UserRole> roleList = new ArrayList<UserRole>();
        	           
        	            // 用户角色
        	            if (StringHelper.isNotBlank(roleIds)) {
        	                String[] roleArray = roleIds.split(",");
        	                for (String roleId : roleArray) {
        	                    UserRole urTemp = new UserRole();

        	                    urTemp.setUserId(sysUser.getId());
        	                    urTemp.setRoleId(roleId);
        	                    roleList.add(urTemp);
        	                }
        	            }
        	            result = sysUserService.addUser(sysUser, roleList);
        				
        				
        				result = marketUserService.regUser(regUser,createToken,invitingUser,topInviting);
            			//返回数据
        				Map<String, Object> dataMap = new HashMap<String,Object>(); 
        				dataMap.put("accessToken", createToken.getAccessToken());
        				dataMap.put("expiredTime", createToken.getExpiredTime());
        				resultMap.put(DATA, dataMap);
            			errorCode = SUCCESS_ERROR_CODE;
                    	errorMsg = SUCCESS_ERROR_MSG;
        			}else{
        				result = FAIL;
        				errorCode = OPENID_EXIST_ERROR_CODE;
        				errorMsg =  OPENID_EXIST_ERROR_MSG;
        			}
    			}else{
        			result = FAIL;
        			errorCode = INVITING_ERROR_CODE;
                	errorMsg = INVITING_ERROR_MSG;
    			}
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	log(e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
     */
	
	/**
	 * 添加手机号码，验证码的登入
	 * @return
	 */
	@RequestMapping(value="/phone/in")
    @ResponseBody
    public Map<String,Object> in(HttpServletRequest request,HttpServletResponse response,String phone,String code){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		
    		//判断必要的参数
    		if( StringHelper.isNotBlank(phone) && StringHelper.isNotBlank(code) ){
    			//判断手机号码
    			if( isPhoneCode(phone, code) ){
    				//判断手机号码有没有
        			MarketUser user = getMarketUserByPhone(phone);
        			if( null != user ){
        				//生成新的TOKEN
        				MarketToken createToken = null;
        				//直接生成新的TOKEN返回 用户
	    				createToken = createToken(user);
	    				
	    				String addResult = marketTokenService.add(createToken);
	    				if( SUCCESS.equals(addResult) ){
	    					result = SUCCESS;
	    	    			errorCode = SUCCESS_ERROR_CODE;
	    	            	errorMsg = SUCCESS_ERROR_MSG;
	    	            	Map<String, Object> dataMap = new HashMap<String,Object>();
	    	            	dataMap.put("accessToken", createToken.getAccessToken());
	    	            	dataMap.put("expiredTime", createToken.getExpiredTime());
	    	            	dataMap.put("userId", user.getId());
	    	            	resultMap.put(DATA, dataMap);
	    	            	
	    				}
        			}else{
        				result = FAIL;
    	    			errorCode = WEIXIN_AUTH_ERROR_CODE;
    	            	errorMsg = WEIXIN_AUTH_ERROR_MSG;
        			}
    			}else{
    				result = FAIL;
	    			errorCode = PHONE_CODE_ERROR_CODE;
	            	errorMsg = PHONE_CODE_ERROR_MSG;
    			}
    		}
    		
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	//logException("MallLoginInterface", "in", e.toString(),"商城登入接口",e);
    		
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } 

	
	
	
    /**
     * APP用户注册成商家
     * @return
     */
    @RequestMapping(value="/reg")
    @ResponseBody
    public Map<String,Object> reg(HttpServletRequest request,HttpServletResponse response,String openid,String unionId,String userNickName,String userHeadImg,String invitingCode){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(unionId ) && StringHelper.isNotBlank(invitingCode) ){
    			//验证邀请码是否正确
    			MarketUser invitingUser = marketUserService.getUserByInvitingCode(invitingCode);
    			
    			if( null != invitingUser ){
    				
    				MarketUser usr = null;
    				//验证opendid 是否注册 
        			//MarketUser openExisted = marketUserService.getUserByOpenid(openid);
        			MarketUser unionExisted = marketUserService.getUserByUnionId(unionId);
    				//MarketUser nameExisted = marketUserService.getUserByName(userNickName);
    				
    				
        			if( unionExisted != null ){
        				usr = unionExisted;
        			}
        			
    				
        			if( null == usr ){
        				MarketUser regUser = regUser(openid, unionId, userHeadImg, userNickName, invitingUser.getId());
            			//生成一个TOKEN 
        				MarketToken createToken = createToken(regUser);
            			//更新数据库
        				
        				String onePeople="0";
        				if( StringHelper.isNotBlank(invitingUser.getSuccessPeople()) ){
        					onePeople = invitingUser.getSuccessPeople();
        				}
        				onePeople = NumberStringHelper.addString(onePeople, "1");
        				invitingUser.setSuccessPeople(onePeople);
        				//推送消息到云店主
        				
        				//判断有没有上上级
        				MarketUser topInviting = marketUserService.get(invitingUser.getInvitingId());
        				if( null != topInviting ){
        					String topPeople="0";
        					if( StringHelper.isNotBlank(topInviting.getSuccessPeople()) ){
        						topPeople = topInviting.getSuccessPeople();
            				}
        					topPeople = NumberStringHelper.addString(topPeople, "1");
        					topInviting.setSuccessPeople(topPeople);
        					
        					//推送消息到云店主
        				}
        				
        				 String roleIds = sysSettingService.getByKey("MARKET_ROLE_ID");
        				 String orgCode = sysSettingService.getByKey("MARKET_ORG_CODE");
        				//添加一个登入后台的用户
        				SysUser sysUser = new SysUser();
        				sysUser.setUsername(regUser.getInvitingCode());//邀请码作为用户的登入名称
        				String realName = "";
        				if( StringHelper.isNotBlank(regUser.getUserNickName()) ){
        					realName = regUser.getUserNickName();
        				}else{
        					realName = "匿名用户";
        					regUser.setUserNickName("匿名用户");
        				}
        				sysUser.setRealname(realName);
        				
        				sysUser.setOrg(orgCode);
        				sysUser.setType("1");
        				sysUser.setIsUsable("1");
        	            sysUser.setId(IdGen.uuid());
        	            sysUser.setPassword(MD5Helper.md5DoubleSalt(RESET_PWD, sysUser.getUsername()));

        	            List<UserRole> roleList = new ArrayList<UserRole>();
        	           
        	            // 用户角色
        	            if (StringHelper.isNotBlank(roleIds)) {
        	                String[] roleArray = roleIds.split(",");
        	                for (String roleId : roleArray) {
        	                    UserRole urTemp = new UserRole();

        	                    urTemp.setUserId(sysUser.getId());
        	                    urTemp.setRoleId(roleId);
        	                    roleList.add(urTemp);
        	                }
        	            }
        	            result = sysUserService.addUser(sysUser, roleList);
        				
        				
        				result = marketUserService.regUser(regUser,createToken,invitingUser,topInviting);
        				
        				if( invitingUser != null ){
        					//pushMsg("测试一下");
        					pushMsg(invitingUser.getId(),"恭喜您成功邀请"+userNickName+"成为云店主！");
            				if( topInviting != null ){
            					//推送消息到云店主
            					pushMsg(topInviting.getId(),"恭喜您的下级成功邀请"+userNickName+"成为云店主！");
            				}
        				}
        				
            			//返回数据
        				Map<String, Object> dataMap = new HashMap<String,Object>(); 
        				dataMap.put("accessToken", createToken.getAccessToken());
        				dataMap.put("expiredTime", createToken.getExpiredTime());
        				dataMap.put("userId", regUser.getId());
        				resultMap.put(DATA, dataMap);
            			errorCode = SUCCESS_ERROR_CODE;
                    	errorMsg = SUCCESS_ERROR_MSG;
        			}else{
        				result = FAIL;
        				errorCode = OPENID_EXIST_ERROR_CODE;
        				errorMsg =  OPENID_EXIST_ERROR_MSG;
        			}
    			}else{
        			result = FAIL;
        			errorCode = INVITING_ERROR_CODE;
                	errorMsg = INVITING_ERROR_MSG;
    			}
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	log(e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
  
    
    /**
     * APP用户注册成商家
     * @return
     */
    @RequestMapping(value="/isyun")
    @ResponseBody
    public Map<String,Object> isyun(HttpServletRequest request,HttpServletResponse response,String unionId){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(unionId ) ){
    			MarketUser user = getMarketUserByUnionId(unionId);
    			
    			if( null != user ){
    				//二维码链接 
    				String URL = sysSettingService.getByKey("INVITE_SEND_URL_SIZE");
    				String[] split = URL.split(",");
    				String inviteUrl = split[0];
    				inviteUrl += user.getInvitingCode();
    				
    				String size = split[1];
    				String url =QcodeUtils.create(inviteUrl, Integer.parseInt(size), Integer.parseInt(size), "png");
    				
    				resultMap.put(DATA, url);
    				result = SUCCESS;
    				errorCode = SUCCESS_ERROR_CODE;
    	        	errorMsg = SUCCESS_ERROR_MSG;
    			}else{
    				errorCode = YUN_NOT_ERROR_CODE;
    	        	errorMsg = YUN_NOT_ERROR_MSG;
    			}
    			
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	log(e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
    
    /**
     * APP用户注册成商家
     * @return
     */
    @RequestMapping(value="/regnew")
    @ResponseBody
    public Map<String,Object> regnew(HttpServletRequest request,HttpServletResponse response,String openid,String unionId,String userNickName,String userHeadImg,String phone,String code){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(unionId ) && StringHelper.isNotBlank(phone) && StringHelper.isNotBlank(code) ){
    			//验证邀请码是否正确
    			MarketUser invitingUser = marketUserService.getUserByInvitingCode("171107");
    			
    			//ver
    			boolean  isCode = isPhoneCode(phone, code);
    			
    			if( null != invitingUser && isCode ){
    				
    				MarketUser usr = null;
    				//验证opendid 是否注册 
        			//MarketUser openExisted = marketUserService.getUserByOpenid(openid);
        			MarketUser unionExisted = marketUserService.getUserByUnionId(unionId);
    				//MarketUser nameExisted = marketUserService.getUserByName(userNickName);
    				
    				
        			if( unionExisted != null ){
        				usr = unionExisted;
        			}
        			
    				
        			if( null == usr ){
        				MarketUser regUser = regUser(openid, unionId, userHeadImg, userNickName, invitingUser.getId(),phone);
            			//生成一个TOKEN 
        				MarketToken createToken = createToken(regUser);
            			//更新数据库
        				
        				String onePeople="0";
        				if( StringHelper.isNotBlank(invitingUser.getSuccessPeople()) ){
        					onePeople = invitingUser.getSuccessPeople();
        				}
        				onePeople = NumberStringHelper.addString(onePeople, "1");
        				invitingUser.setSuccessPeople(onePeople);
        				//推送消息到云店主
        				
        				//判断有没有上上级
        				MarketUser topInviting = marketUserService.get(invitingUser.getInvitingId());
        				if( null != topInviting ){
        					String topPeople="0";
        					if( StringHelper.isNotBlank(topInviting.getSuccessPeople()) ){
        						topPeople = topInviting.getSuccessPeople();
            				}
        					topPeople = NumberStringHelper.addString(topPeople, "1");
        					topInviting.setSuccessPeople(topPeople);
        					
        					//推送消息到云店主
        				}
        				
        				 String roleIds = sysSettingService.getByKey("MARKET_ROLE_ID");
        				 String orgCode = sysSettingService.getByKey("MARKET_ORG_CODE");
        				//添加一个登入后台的用户
        				SysUser sysUser = new SysUser();
        				sysUser.setUsername(regUser.getInvitingCode());//邀请码作为用户的登入名称
        				String realName = "";
        				if( StringHelper.isNotBlank(regUser.getUserNickName()) ){
        					realName = regUser.getUserNickName();
        				}else{
        					realName = "匿名用户";
        					regUser.setUserNickName("匿名用户");
        				}
        				sysUser.setRealname(realName);
        				
        				sysUser.setOrg(orgCode);
        				sysUser.setType("1");
        				sysUser.setIsUsable("1");
        	            sysUser.setId(IdGen.uuid());
        	            sysUser.setPassword(MD5Helper.md5DoubleSalt(RESET_PWD, sysUser.getUsername()));

        	            List<UserRole> roleList = new ArrayList<UserRole>();
        	           
        	            // 用户角色
        	            if (StringHelper.isNotBlank(roleIds)) {
        	                String[] roleArray = roleIds.split(",");
        	                for (String roleId : roleArray) {
        	                    UserRole urTemp = new UserRole();

        	                    urTemp.setUserId(sysUser.getId());
        	                    urTemp.setRoleId(roleId);
        	                    roleList.add(urTemp);
        	                }
        	            }
        	            result = sysUserService.addUser(sysUser, roleList);
        				
        				
        				result = marketUserService.regUser(regUser,createToken,invitingUser,topInviting);
        				
        				if( invitingUser != null ){
        					//pushMsg("测试一下");
        					pushMsg(invitingUser.getId(),"恭喜您成功邀请"+userNickName+"成为云店主！");
            				if( topInviting != null ){
            					//推送消息到云店主
            					pushMsg(topInviting.getId(),"恭喜您的下级成功邀请"+userNickName+"成为云店主！");
            				}
        				}
        				
            			//返回数据
        				Map<String, Object> dataMap = new HashMap<String,Object>(); 
        				dataMap.put("accessToken", createToken.getAccessToken());
        				dataMap.put("expiredTime", createToken.getExpiredTime());
        				dataMap.put("userId", regUser.getId());
        				
        				//二维码链接 
        				String URL = sysSettingService.getByKey("INVITE_SEND_URL_SIZE");
        				String[] split = URL.split(",");
        				String inviteUrl = split[0];
        				inviteUrl += regUser.getInvitingCode();
        				
        				String size = split[1];
        				String url =QcodeUtils.create(inviteUrl, Integer.parseInt(size), Integer.parseInt(size), "png");
        				
        				dataMap.put("url", url );
        				
        				resultMap.put(DATA, dataMap);
            			errorCode = SUCCESS_ERROR_CODE;
                    	errorMsg = SUCCESS_ERROR_MSG;
        			}else{
        				result = FAIL;
        				errorCode = OPENID_EXIST_ERROR_CODE;
        				errorMsg =  OPENID_EXIST_ERROR_MSG;
        			}
    			}else{
        			result = FAIL;
        			errorCode = PHONE_CODE_ERROR_CODE;
                	errorMsg = PHONE_CODE_ERROR_MSG;
    			}
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	log(e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
    
    
    
    
    
    @RequestMapping(value="/pushMsg")
    @ResponseBody
    public void pushMsg( String userId ,String text ){
    	//推送消息到云店主
		 JPushClient jpushClient = new JPushClient(SECREAT, APP_KEY, null, ClientConfig.getInstance());

	    // For push, all you need do is to build PushPayload object.
	    //PushPayload payload = buildPushObject_all_all_alert( text );
	    
		//PushPayload payload = buildPushObject_ios_audienceMore_messageWithExtras( userId,text );
		PushPayload payload = buildPushObject_all_alias_alert(userId,text);
	    try {
	        PushResult tmpres = jpushClient.sendPush(payload);
	       
	        System.out.println(tmpres);
	        //LOG.info("Got result - " + result);

	    } catch (APIConnectionException e) {
	        // Connection error, should retry later
	        //LOG.error("Connection error, should retry later", e);
	    	System.out.println(1);
	    } catch (APIRequestException e) {
	        // Should review the error, and fix the request
	        //LOG.error("Should review the error, and fix the request", e);
	        //LOG.info("HTTP Status: " + e.getStatus());
	       // LOG.info("Error Code: " + e.getErrorCode());
	        //LOG.info("Error Message: " + e.getErrorMessage());
	    	System.out.println(2);
	    }
	    
    }

    public static PushPayload buildPushObject_all_all_alert( String text ) {
        return PushPayload.alertAll(text);
    }
    
    public static PushPayload buildPushObject_all_alias_alert( String userId, String text ) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(userId))
                .setNotification(Notification.alert(text))
                .build();
    }
    
    public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras( String userId,String text ) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.tag(userId))
                        //.addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent(text)
                        //.addExtra("from", "JPush")
                        .build())
                .build();
    }

    
    /**
     * APP用户登入APP
     * @return
     */
    @RequestMapping(value="/in")
    @ResponseBody
    public Map<String,Object> in(HttpServletRequest request,HttpServletResponse response,String openid,String unionId,String userNickName,String userHeadImg,String name,String token, String phone, String code ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
			
			//用户token登入
			if( StringHelper.isNotBlank(token) ){
				//验证TOKEN的有效性
				MarketUser user = getMarketUserByToken(token);
				if( null != user ){
					MarketToken tokenByToken = marketTokenService.getMarketTokenByToken(token);
					result = SUCCESS;
					Map<String, Object> dataMap = new HashMap<String,Object>();
					dataMap.put("accessToken", tokenByToken.getAccessToken());
	    			dataMap.put("expiredTime", tokenByToken.getExpiredTime());
	    			dataMap.put("userId", user.getId());
	    			resultMap.put(DATA, dataMap);
					errorCode = SUCCESS_ERROR_CODE;
		        	errorMsg = SUCCESS_ERROR_MSG;
				}else{
					errorCode = TOKEN_ERROR_CODE;
		        	errorMsg = TOKEN_ERROR_MSG;
				}
			}else{
				//用户公众号登入
    			if( StringHelper.isNotBlank(unionId) ){
    				//用户APP登入
        			if( StringHelper.isNotBlank(unionId) ){
        				MarketUser user = getMarketUserByUnionId(unionId);
        				if( null != user ){
        					MarketToken createToken = createToken(user);
        		        	result = marketTokenService.add(createToken);
        		        	user.setUserNickName(userNickName);
        		        	user.setUserHeadImg(userHeadImg);
        		        	marketUserService.edit(user);
        		        	
        		        	Map<String, Object> dataMap = new HashMap<String,Object>();
        		        	dataMap.put("accessToken", createToken.getAccessToken());
        	    			dataMap.put("expiredTime", createToken.getExpiredTime());
        	    			dataMap.put("userId", user.getId());
        	    			resultMap.put(DATA, dataMap);
        					errorCode = SUCCESS_ERROR_CODE;
        		        	errorMsg = SUCCESS_ERROR_MSG;
        				}else{
            				errorCode = UNIONID_ERROR_CODE;
        		        	errorMsg = UNIONID_ERROR_MSG;
            			}
        			}
    			}
			}
			
		
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	log(e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
    
    /**
     * APP用户登入APP
     * @return
     */
    @RequestMapping(value="/out")
    @ResponseBody
    public Map<String,Object> out(HttpServletRequest request,HttpServletResponse response,String token ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) ){
    			//根据TOKEN查找用户
    			MarketUser user = getMarketUserByToken(token);
    			if( null != user ){
    			    //将TOKEN 删除 
    				result = marketTokenService.deleteByAccessToken(token);
    				errorCode = SUCCESS_ERROR_CODE;
		        	errorMsg = SUCCESS_ERROR_MSG;
    			}else{
    				result = FAIL;
    				errorCode = LOGIN_ERROR_CODE;
    	        	errorMsg = LOGIN_ERROR_MSG;
    			}
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	log(e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }


    /**
     * 注册新用户
     * @return
     */
    public MarketUser regUser( String openid,String unionId,String userHeadImg,String userNickName,String invitingId ){
    	String userId = IdGen.uuid();
		Date date = new Date();
		String code = getRandomInvitingCode();//本人的新产生的邀请码
		
		MarketUser user = new MarketUser();
		
		//6个必填字段
		user.setId(userId);
		user.setIsEffective(DBConst.TRUE);
		user.setCreateUser(CREATE_USER);
		user.setCreateTime(date);
		user.setUpdateTime(date);
		user.setOrgCode(ORG_CODE);
		
		//关联字段
		user.setInvitingId(invitingId);
		//业务字段 
		
		if(containsEmoji(userNickName)){
			user.setUserNickName(filterEmoji(userNickName));
		}else{
			user.setUserNickName(userNickName);
		}
		user.setUserHeadImg(userHeadImg);
		user.setInvitingCode(code);//本人的邀请 码
		user.setMoney("0");//当前余额
		user.setOpenid(openid);//用户公众号的OPENTID
		user.setUnionId(unionId);//微信 统一 ID
		user.setPreProfit("0");//用户待收益
		user.setTotalProfit("0");//用户总收益
		user.setTotalProduct("0");//商品总成交数量
		
		//addNewTgw(user);
    	return user;
    }
    
    /** 
     * 检测是否有emoji字符 
     * 
     * @param source 
     * @return 一旦含有就抛出 
     */  
    public static boolean containsEmoji(String source) {  
        if (StringUtils.isBlank(source)) {  
            return false;  
        }  
        int len = source.length();  
        for (int i = 0; i < len; i++) {  
            char codePoint = source.charAt(i);  
            if (!isNotEmojiCharacter(codePoint)) {  
                //判断到了这里表明，确认有表情字符  
                return true;  
            }  
        }  
        return false;  
    }  
  
    /** 
     * 判断是否为非Emoji字符 
     * 
     * @param codePoint 比较的单个字符 
     * @return 
     */  
    private static boolean isNotEmojiCharacter(char codePoint) {  
        return (codePoint == 0x0) ||  
                (codePoint == 0x9) ||  
                (codePoint == 0xA) ||  
                (codePoint == 0xD) ||  
                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||  
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||  
                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));  
    }  
  
    /** 
     * 过滤emoji 或者 其他非文字类型的字符 
     * 
     * @param source 
     * @return 
     */  
    public static String filterEmoji(String source) {  
        if (StringUtils.isBlank(source)) {  
            return source;  
        }  
        if (!containsEmoji(source)) {  
            return source;//如果不包含，直接返回  
        }  
        StringBuilder buf = new StringBuilder();  
        int len = source.length();  
        for (int i = 0; i < len; i++) {  
            char codePoint = source.charAt(i);  
            if (isNotEmojiCharacter(codePoint)) {  
                buf.append(codePoint);  
            }  
        }  
  
        return buf.toString().trim();  
    }  
    
    
    /**
     * 注册新用户
     * @return
     */
    public MarketUser regUser( String openid,String unionId,String userHeadImg,String userNickName,String invitingId,String phone ){
    	String userId = IdGen.uuid();
		Date date = new Date();
		String code = getRandomInvitingCode();//本人的新产生的邀请码
		
		MarketUser user = new MarketUser();
		
		//6个必填字段
		user.setId(userId);
		user.setIsEffective(DBConst.TRUE);
		user.setCreateUser(CREATE_USER);
		user.setCreateTime(date);
		user.setUpdateTime(date);
		user.setOrgCode(ORG_CODE);
		
		//关联字段
		user.setInvitingId(invitingId);
		//业务字段 
		user.setUserPhone(phone);
		user.setUserNickName(filterEmoji(userNickName));
		user.setUserHeadImg(userHeadImg);
		user.setInvitingCode(code);//本人的邀请 码
		user.setMoney("0");//当前余额
		user.setOpenid(openid);//用户公众号的OPENTID
		user.setUnionId(unionId);//微信 统一 ID
		user.setPreProfit("0");//用户待收益
		user.setTotalProfit("0");//用户总收益
		user.setTotalProduct("0");//商品总成交数量
		
		//addNewTgw(user);
    	return user;
    }
    
    /**
     * 根据用户生成一个新的TOKEN
     * @param user
     * @return
     */
    public MarketToken createToken( MarketUser user ){
    	Date date = new Date();
    	//六个必须字段
    	MarketToken token = new MarketToken();
    	token.setId(IdGen.uuid());
    	token.setIsEffective(DBConst.TRUE);
    	token.setCreateTime(date);
    	token.setUpdateTime(date);
    	token.setOrgCode(ORG_CODE);
    	token.setCreateUser(CREATE_USER);
    	//关联字段
    	token.setUserId(user.getId());//关联用户ID
    	//三个业务字段
    	token.setType("1");//0代表友惠家商城TOKEN
    	String unionId = "";
    	if( StringHelper.isNotBlank(user.getUnionId()) ){
    		unionId = user.getUnionId();
    	}
    	String openid = "";
    	if( StringHelper.isNotBlank(user.getOpenid()) ){
    		openid = user.getOpenid();
    	}
    	
    	
    	token.setUnionId(unionId);//微信统一 ID
    	token.setOpenid(openid);//微信公众号ID
    	token.setAccessToken(getToken());//设置TOKEN
    	token.setExpiredTime(getExpiredTimeToken(date));//设置有效期
    	
    	return token;
    }
    
    @RequestMapping(value="/test")
    @ResponseBody
    public String test(String code){
    	String roleIds = sysSettingService.getByKey("MARKET_ROLE_ID");
		 String orgCode = sysSettingService.getByKey("MARKET_ORG_CODE");
    	//添加一个登入后台的用户
		SysUser sysUser = new SysUser();
		sysUser.setUsername(code);//邀请码作为用户的登入名称
		sysUser.setRealname("小宝");
		sysUser.setOrg(orgCode);
		sysUser.setType("1");
		sysUser.setIsUsable("1");
        sysUser.setId(IdGen.uuid());
        sysUser.setPassword(MD5Helper.md5DoubleSalt(RESET_PWD, sysUser.getUsername()));

        List<UserRole> roleList = new ArrayList<UserRole>();
       
        // 用户角色
        if (StringHelper.isNotBlank(roleIds)) {
            String[] roleArray = roleIds.split(",");
            for (String roleId : roleArray) {
                UserRole urTemp = new UserRole();

                urTemp.setUserId(sysUser.getId());
                urTemp.setRoleId(roleId);
                roleList.add(urTemp);
            }
        }
        return  sysUserService.addUser(sysUser, roleList);
        
		
    }
    
    /**
     * 注册新用户时添加一条新申请推广位信息
     * @param user
    
    public void addNewTgw( MarketUser user ){
    	SyncTgw syncTgw = new SyncTgw();
    	syncTgw.setUserId(user.getId());
    	syncTgw.setUnionid(user.getUnionId());
    	syncTgw.setUserNickName(user.getUserNickName());
    	syncTgwService.add(syncTgw);
    } */
    
    
}